package com.student.health.controller;

import com.student.health.entity.User;
import com.student.health.service.UserService;
import com.student.health.utils.DTO.ProjectUrlConfig;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @Author: xx
 * @Date: 2024-04-03 12:31
 * @Description:
 * @Version 1.0
 */
@RequestMapping("/api/weChat")
@Controller
public class WechatController {

    @Autowired
    private WxMpService wxOpenService;
    @Autowired
    private ProjectUrlConfig projectUrlConfig;

    @Autowired
    private UserService userService;

    @GetMapping("/qrAuthorize")
    public ResponseEntity<String> qrAuthorize(@RequestParam("userId") String userId){
        String redirectUrl = projectUrlConfig.getWechatOpenAuthorize()+"/api/weChat/qrUserInfo";
        String url = wxOpenService.oauth2buildAuthorizationUrl(redirectUrl, WxConsts.OAuth2Scope.SNSAPI_BASE, userId);
        return ResponseEntity.ok(url);
    }

    @GetMapping("/qrUserInfo")
    public ResponseEntity<String> qrUserInfo(@RequestParam("code") String code,
                             @RequestParam("state") String userId){
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();

        try {
            wxMpOAuth2AccessToken = wxOpenService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        String openId = wxMpOAuth2AccessToken.getOpenId();

        User entity = new User();
        entity.setId(Integer.parseInt(userId));
        entity.setOpenId(openId);
        userService.updateById(entity);
        //将会重新访问该前端地址+/#/ 并加上openid的参数完成授权
        return ResponseEntity.ok("绑定成功");
    }
}
